package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<User> sendMsg(HttpSession session, @RequestBody User user){
        if(StringUtils.isNotEmpty(user.getPhone())){
            // 生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            // 发送验证码
//            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", user.getPhone(), code);
            // 保存验证码
//            session.setAttribute(user.getPhone(), code);
            // 优化：redis保存验证码
            redisTemplate.opsForValue().set(user.getPhone(), code, 5L, TimeUnit.MINUTES);
            log.info("phone:{}, code:{}", user.getPhone(), code);
            return R.success(user);
        }else {
            return R.error("失败");
        }
    }

    @PostMapping("/login")
    public R<User> login(HttpSession session, @RequestBody Map user){
        String phone = user.get("phone").toString();
//        String code = (String) session.getAttribute(phone);
        // 优化：从redis中取出验证码
        String code = (String) redisTemplate.opsForValue().get(phone);
        String userCode = user.get("code").toString();
        if(userCode!=null && userCode.equals(code)){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone, phone);
            User user1 = userService.getOne(userLambdaQueryWrapper);
            if(user1 == null){
                user1 = new User();
                user1.setPhone(phone);
                user1.setStatus(1);
                userService.save(user1);
            }
            session.setAttribute("user", user1.getId());
            // 登录成功从redis中删除缓存
            redisTemplate.delete(user1.getPhone());
            return R.success(user1);
        }else {
            return R.error("验证码错误！");
        }
    }

}
